package com.dlc.shop.live.api.controller;

import cn.hutool.core.util.StrUtil;
import com.dlc.shop.common.bean.AliLive;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.live.common.service.LiveRoomService;
import com.dlc.shop.live.common.util.AliLiveUtil;
import com.dlc.shop.live.common.vo.LiveRoomVO;
import com.dlc.shop.security.api.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


/**
 * @author TRAKC
 */
@RestController
@RequestMapping("/p/live/liveRoom")
@Tag(name = "我的直播接口")
@AllArgsConstructor
public class MyLiveRoomController {

    private final LiveRoomService liveRoomService;
    private final ShopConfig shopConfig;

    @GetMapping("/getUserLivingRoom")
    @Operation(summary = "主播获取当前正在开播的直播间信息")
    public ServerResponseEntity<LiveRoomVO> getUserLivingRoom() {
        String userId = SecurityUtils.getUser().getUserId();
        LiveRoomVO livingRoom = getLivingRoom(userId);
        return ServerResponseEntity.success(livingRoom);
    }

    private LiveRoomVO getLivingRoom(String userId) {
        LiveRoomVO livingRoom = liveRoomService.getByUserId(userId);
        if (Objects.isNull(livingRoom)) {
            // 当前未有直播权限
            throw new YamiShopBindException("yami.live.user.auth.not.exist");
        }
        long currentTimeMillis = System.currentTimeMillis();
        if (livingRoom.getStartTime().getTime() > currentTimeMillis) {
            // 未到直播开始时间
            throw new YamiShopBindException("yami.live.user.auth.not.start");
        }
        return livingRoom;
    }

    @GetMapping("/getPushUrl")
    @Operation(summary = "获取推流地址", description = "获取推流地址")
    public ServerResponseEntity<String> getPushUrl() {
        AliLive aliLive = shopConfig.getAliLive();
        if (Objects.isNull(aliLive) || StrUtil.isBlank(aliLive.getAppName())) {
            // 无法获取到直播配置
            throw new YamiShopBindException("yami.live.config.not.exist");
        }
        String userId = SecurityUtils.getUser().getUserId();
        LiveRoomVO livingRoom = getLivingRoom(userId);
        // 不超过256字符 支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)
        // {appName}-{roomId}-{shopId}-{userId}
        String streamName = StrUtil.format("{}-{}-{}-{}", aliLive.getAppName(), livingRoom.getRoomId(), livingRoom.getShopId(), livingRoom.getUserId());
        String pushUrl = AliLiveUtil.getPushUrl(streamName, livingRoom.getEndTime(), aliLive);
        return ServerResponseEntity.success(pushUrl);
    }
}
